package com.kika.obwiki.config.xss;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(urlPatterns = "/*") // 过滤所有请求
public class XssFilter implements Filter {
    /**
     * 不进行XSS过滤的URL
     */
    private static final String[] NO_FILTER_URLS = { "/doc/save" };

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String uri = request.getRequestURI();
        boolean isFilter = true;
        for (String noFilterUrl : NO_FILTER_URLS) {
            if (noFilterUrl.equals(uri)) {
                isFilter = false;
                break;
            }
        }
        if (!isFilter) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            XssHttpServletRequestWrapper wrapper = new XssHttpServletRequestWrapper(request);
            filterChain.doFilter(wrapper, servletResponse);
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}